import re
import os
from collections import namedtuple
from itertools import groupby
import shutil

ImageInfo = namedtuple('ImageInfo', 'full num type date')
top_dir = r'C:\Users\yang.lei\Downloads\test_file'
all_dir = os.path.join(top_dir, 'all')
result_dir = os.path.join(top_dir, 'result')
os.makedirs(result_dir, exist_ok=True)
# reg_imageinfo = re.compile(r'Test_+(\d+)_+(Verify|Register)_+(\d+).jpg')
reg_imageinfo = re.compile(r'.+?Test.+?(\d{10,}).+?(Verify|Register).+?(\d{10,})')
VERIFY = 'Verify'
REGISTER = 'Register'
VERIFY_MIN_COUNT = 1
REGISTER_MIN_COUNT = 5


def test_regex():
    print(reg_imageinfo.match(
        'PD2056_Test_Dataset_1_865386053570930_XVXV_Verify_KW_1_VP_1_Success_1634379257162_Contain_None_None.pcm'))


def extract_imageinfo(file):
    m = reg_imageinfo.search(file)
    if m:
        return ImageInfo(file, m.group(1), m.group(2), m.group(3))
    else:
        print(f'{file} not valid file name !!!!!!!!!!!!!!!!!!!!!!!!')


def copy_images_to_des_dir(images, des_dir):
    for image in images:
        shutil.copy2(image.full, des_dir)
        print(f'copied {image.full} to {des_dir}')


def copy_typed_images_to_sub_dir(num_dir, type, images):
    typed_sub_dir = os.path.join(num_dir, type)
    os.makedirs(typed_sub_dir, exist_ok=True)
    copy_images_to_des_dir(images, typed_sub_dir)


if __name__ == "__main__":
    all_image_infos = []
    for f in os.listdir(all_dir):
        full = os.path.join(all_dir, f)
        image_info = extract_imageinfo(full)
        if image_info:
            all_image_infos.append(image_info)
    for num, g in groupby(all_image_infos, lambda x: x.num):
        # print(num)
        images = list(g)
        # print(images)
        register_images = [i for i in images if i.type == REGISTER]
        verify_images = [i for i in images if i.type == VERIFY]
        if len(register_images) < REGISTER_MIN_COUNT or len(verify_images) < VERIFY_MIN_COUNT:
            continue
        num_dir = os.path.join(result_dir, num)
        os.makedirs(num_dir, exist_ok=True)
        copy_typed_images_to_sub_dir(num_dir, VERIFY, verify_images)
        latest_register_images = sorted(register_images, key=lambda x: x.date, reverse=True)[:REGISTER_MIN_COUNT]
        copy_typed_images_to_sub_dir(num_dir, REGISTER, latest_register_images)
    print('end')
